import strawberry
from app.common.auth import authenticate_user
from app.common.auth import create_access_token
from app.common.errors import ApiError
from app.common.errors import Error
from settings import Config


@strawberry.type
class Token:
    token: str


@strawberry.mutation
async def login_field(username: str, password: str) -> Token:
    user = await authenticate_user(username, password)
    if not user:
        raise ApiError(Error.AuthError)

    permissions = await user.permissions.all().only("number")

    token = create_access_token(
        data={
            "username": user.username,
            "id": user.auto_id,
            "permissions": [permission.number.value for permission in permissions],
        },
        expires_delta=Config.TOKEN_EXPIRE_TIME,
    )

    return Token(token=token)
